﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VioletDevelopmentLaboratory.Net.Web;
using VioletDevelopmentLaboratory.Net.Web.Component;
using VioletDevelopmentLaboratory.Net.Web.WebControls;

public partial class vboard_component_board_template_default_form_sub : BoardSubPartBase
{
	private BoardCategoryCollection CurrentCategoryCollection;
	private BoardThread CurrentThread;
	private AttachmentFileInfoCollection CurrentAttachmentFileInfoCollection;
	private Vote CurrentVote;

	private String getThreadModifyCancelUrl()
	{
		String url = BoardUtil.GetBoardUrl(BoardPart.View, BoardParameters.PageIndex, BoardParameters.CategoryID, BoardParameters.ThreadID, BoardParameters.SearchText, 0, 0);

		if (BoardParameters.Part == BoardPart.Form_Add && String.IsNullOrEmpty(BoardParameters.ThreadID))
			url = BoardUtil.GetBoardUrl(BoardPart.List, BoardParameters.PageIndex, BoardParameters.CategoryID, "", BoardParameters.SearchText, 0, 0);

		return url;
	}



	protected void Page_Init(Object sender, EventArgs e)
	{
		this.CurrentCategoryCollection = (BoardCategoryCollection)Page.Items["CurrentCategoryCollection"];
		this.CurrentThread = (BoardThread)this.Page.Items["CurrentThread"];
		this.CurrentAttachmentFileInfoCollection = (AttachmentFileInfoCollection)this.Page.Items["CurrentAttachmentFileInfoCollection"];
		this.CurrentVote = (Vote)this.Page.Items["CurrentVote"];
	}

	protected void Page_Load(Object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			this.CategoryDrowDownList_Bind();

			ThreadMultiFileUpload.UploadLimit = base.CurrentBoard.FileUploadLimit;
			ThreadMultiFileUpload.UploadSizeLimit = base.CurrentBoard.FileUploadSizeLimit;
			ThreadMultiFileUpload.UploadExtensions = base.CurrentBoard.FileUploadExtension;
			ThreadMultiFileUpload.RuleMessage = String.Format(GetLocalResourceObject("MultiFileUploadRuleMessageFormat").ToString(),
				base.CurrentBoard.FileUploadLimit,
				base.CurrentBoard.FileUploadExtension.ToUpper().Replace(";", ", "),
				VUtility.GetFormatFileLength(Convert.ToInt64(base.CurrentBoard.FileUploadSizeLimit) * 1024),
				GetLocalResourceObject("FileDescription"));
			ThreadMultiFileUpload.CurrentUserIsAdministrator = (base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard));

			CancelHyperLink.NavigateUrl = this.getThreadModifyCancelUrl();
		}

		if (BoardParameters.Part == BoardPart.Form_Add)
		{
			#region Add
			if (!Page.IsPostBack)
			{
				//투표폼 설정
				VotePlaceHolder.Visible = base.CurrentBoard.UseVote;

				BeginDateTextBox.Text = String.Format("{0:yyyy-MM-dd hh:mm:ss}", DateTime.Now);

				FilePlaceHolder.Visible = base.CurrentBoard.UseFileUpload && (base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.FileUpload));

				IsAnnoCheckBox.Visible = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.AnnoWrite);

				IsClosedCheckBox.Visible = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard);

				//답변모드일때
				if (BoardParameters.Part == BoardPart.Form_Add && !String.IsNullOrEmpty(BoardParameters.ThreadID))
				{
					if (!String.IsNullOrEmpty(this.CurrentThread.CategoryID))
					{
						ListItem selectedItem = CategoryDropDownList.Items.FindByValue(this.CurrentThread.CategoryID);
						if (selectedItem != null)
							selectedItem.Selected = true;
					}

					TitleTextBox.Text = String.Format(GetLocalResourceObject("ReplyTitleFormat").ToString(), this.CurrentThread.Title);

					CategoryDropDownList.Focus();
				}
			}
			#endregion
		}
		else
		{
			#region Modify
			if (!Page.IsPostBack)
			{
				if (base.CurrentBoard.UseVote && (this.CurrentVote == null))
				{
					//투표폼 설정
					VotePlaceHolder.Visible = true;
					BeginDateTextBox.Text = String.Format("{0:yyyy-MM-dd hh:mm:ss}", DateTime.Now);
				}
				else
				{
					VotePlaceHolder.Visible = false;
				}

				if (!String.IsNullOrEmpty(this.CurrentThread.CategoryID))
				{
					ListItem selectedItem = CategoryDropDownList.Items.FindByValue(this.CurrentThread.CategoryID);
					if (selectedItem != null)
						selectedItem.Selected = true;
				}

				TitleTextBox.Text = this.CurrentThread.Title;
				ContentTextBox.Text = this.CurrentThread.Content;
				IsHTMLCheckBox.Checked = this.CurrentThread.IsHtml;

				if (this.CurrentThread.Tags != null)
				{
					TagTextBox.Text = String.Join(",", this.CurrentThread.Tags);
				}

				AutoMediaFileViewCheckBox.Checked = this.CurrentThread.AutoMediaFileView;
				IsSecretCheckBox.Checked = this.CurrentThread.IsSecret;
				IsAnnoCheckBox.Checked = this.CurrentThread.IsAnno;
				IsClosedCheckBox.Checked = this.CurrentThread.IsClosed;

				IsAnnoCheckBox.Visible = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.AnnoWrite);
				IsClosedCheckBox.Visible = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard);

				if (this.CurrentThread.Links != null)
				{
					foreach (String link in this.CurrentThread.Links)
					{
						LinkTextBox.Text += link + "\r\n";
					}
				}

				//파일 설정
				FilePlaceHolder.Visible = false;

				if (this.CurrentAttachmentFileInfoCollection != null)
				{
					FilePlaceHolder.Visible = true;

					UploadFileInfoCollection uploadFileInfoCollection = new UploadFileInfoCollection();

					foreach (AttachmentFileInfo attachmentFileInfo in this.CurrentAttachmentFileInfoCollection)
					{
						uploadFileInfoCollection.Add(attachmentFileInfo.UploadFile);
					}

					ThreadMultiFileUpload.CurrentUploadFileInfoCollection = uploadFileInfoCollection;
				}
				else if (base.CurrentBoard.UseFileUpload &&
					(base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.FileUpload)))
				{
					FilePlaceHolder.Visible = true;
				}
			}
			#endregion
		}
	}

	protected void CategoryDrowDownList_Bind()
	{
		CategoryDropDownList.DataSource = this.CurrentCategoryCollection;
		CategoryDropDownList.DataTextField = "Name";
		CategoryDropDownList.DataValueField = "CategoryID";
		CategoryDropDownList.DataBind();

		//선택추가
		CategoryDropDownList.Items.Insert(0, new ListItem(GetLocalResourceObject("CategorySelect").ToString(), ""));

		CategoryRequiredFieldValidator.Enabled = base.CurrentBoard.RequiredCategory;
	}

	private String createVote(String threadID)
	{
		switch (Vote.Create(
			base.CurrentBoard.ComponentID,
			threadID,
			VoteQuestionTextBox.Text,
			VoteAnswersTextBox.Text.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries),
			OpeningCheckBox.Checked,
			MultiSelectionCheckBox.Checked,
			DateTime.Parse(BeginDateTextBox.Text),
			DateTime.Parse(EndDateTextBox.Text)))
		{
			case VoteCreateResult.Success:
				return VUtility.GetVWebGlobalResource("Vote_Do_Create_Success");
			case VoteCreateResult.Exists:
				return VUtility.GetVWebGlobalResource("Vote_Do_Create_Exists");
			default:
				return VUtility.GetVWebGlobalResource("Vote_Do_Create_Failure");
		}
	}

	protected void OKButton_Click(Object sender, EventArgs e)
	{
		if (Page.IsValid)
		{
			String[] links = LinkTextBox.Text.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

			String[] files = new String[ThreadMultiFileUpload.CurrentUploadFileInfoCollection.Count];
			for (Int32 i = 0; i < ThreadMultiFileUpload.CurrentUploadFileInfoCollection.Count; i++)
			{
				files[i] = ThreadMultiFileUpload.CurrentUploadFileInfoCollection[i].FileID;
			}

			if (BoardParameters.Part == BoardPart.Form_Add)
			{
				#region Add
				String insertedThreadID;
				Int64 insertedThreadNumber, insertedThreadGroup;

				if (BoardParameters.Part == BoardPart.Form_Add && !String.IsNullOrEmpty(BoardParameters.ThreadID))
				{
					//답변쓰기

					Boolean doReply = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.ThreadReplyWrite);

					if (base.CurrentBoard.UseReply && !this.CurrentThread.IsDeleted && !this.CurrentThread.IsBlocked && !this.CurrentThread.IsClosed && !this.CurrentThread.IsAnno && doReply)
					{
						BoardThreadCreateResult result = base.CurrentBoard.AddThread(
							CategoryDropDownList.SelectedValue,
							this.CurrentThread.ThreadGroup,
							this.CurrentThread.ThreadDepth,
							this.CurrentThread.ThreadIndex,
							base.CurrentUserInfo.Name,
							base.CurrentUserInfo.ProviderUserKey,
							IsAnnoCheckBox.Checked,
							IsSecretCheckBox.Checked,
							IsClosedCheckBox.Checked,
							Page.Request.UserHostAddress,
							links,
							files,
							AutoMediaFileViewCheckBox.Checked,
							TitleTextBox.Text,
							IsHTMLCheckBox.Checked,
							TagTextBox.Text.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries),
							ContentTextBox.Text,
							out insertedThreadID,
							out insertedThreadNumber,
							out insertedThreadGroup
						);

						switch (result)
						{
							case BoardThreadCreateResult.Success:
								String voteCreateResultMessage = VoteFormCheckBox.Checked ? createVote(insertedThreadID) : String.Empty;

								VUtility.GoToMessagePage(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Success") + voteCreateResultMessage,
									BoardUtil.GetBoardUrl(BoardPart.View, 0, "", insertedThreadID, "", 0, 0), true, 3);
								break;
							case BoardThreadCreateResult.Failure:
								VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Failure"), true);
								break;
						}
					}
					else
						VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Rejection"), true);
				}
				else
				{
					Boolean doWrite = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || base.CurrentUserInfo.IsAuthorizedBy(base.CurrentBoard, BoardCommand.ThreadWrite);

					if (doWrite)
					{
						BoardThreadCreateResult result = base.CurrentBoard.AddThread(
							CategoryDropDownList.SelectedValue,
							0,
							-1,
							0,
							base.CurrentUserInfo.Name,
							base.CurrentUserInfo.ProviderUserKey,
							IsAnnoCheckBox.Checked,
							IsSecretCheckBox.Checked,
							IsClosedCheckBox.Checked,
							Page.Request.UserHostAddress,
							links,
							files,
							AutoMediaFileViewCheckBox.Checked,
							TitleTextBox.Text,
							IsHTMLCheckBox.Checked,
							TagTextBox.Text.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries),
							ContentTextBox.Text,
							out insertedThreadID,
							out insertedThreadNumber,
							out insertedThreadGroup
						);

						switch (result)
						{
							case BoardThreadCreateResult.Success:
								String voteCreateResultMessage = VoteFormCheckBox.Checked ? createVote(insertedThreadID) : String.Empty;

								VUtility.GoToMessagePage(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Success") + voteCreateResultMessage,
									BoardUtil.GetBoardUrl(BoardPart.View, 0, "", insertedThreadID, "", 0, 0), true, 3);
								break;
							case BoardThreadCreateResult.Failure:
								VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Failure"), true);
								break;
						}
					}
					else
						VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadWrite_Rejection"), true);
				}
				#endregion
			}
			else
			{
				#region Modify
				Boolean doModify = base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard) || (base.CurrentUserInfo.ProviderUserKey == this.CurrentThread.ProviderUserKey);

				if (!this.CurrentThread.IsDeleted && !this.CurrentThread.IsBlocked && doModify)
				{
					this.CurrentThread.CategoryID = CategoryDropDownList.SelectedValue;
					this.CurrentThread.IsAnno = IsAnnoCheckBox.Checked;
					this.CurrentThread.IsSecret = IsSecretCheckBox.Checked;
					this.CurrentThread.IsClosed = IsClosedCheckBox.Checked;
					this.CurrentThread.IP = Page.Request.UserHostAddress;
					this.CurrentThread.Links = links;
					this.CurrentThread.AutoMediaFileView = AutoMediaFileViewCheckBox.Checked;
					this.CurrentThread.Title = TitleTextBox.Text;
					this.CurrentThread.IsHtml = IsHTMLCheckBox.Checked;
					this.CurrentThread.Tags = TagTextBox.Text.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries);
					this.CurrentThread.Content = ContentTextBox.Text;
					this.CurrentThread.LastUpdateBy = Page.User.Identity.Name;

					switch (this.CurrentThread.Modify(files))
					{
						case BoardThreadUpdateResult.Success:
							String voteCreateResultMessage = "";

							if (this.CurrentVote == null && VoteFormCheckBox.Checked)
								voteCreateResultMessage = createVote(this.CurrentThread.ThreadID);

							VUtility.GoToMessagePage(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadUpdate_Success") + voteCreateResultMessage,
								BoardUtil.GetBoardUrl(BoardPart.View, BoardParameters.PageIndex, BoardParameters.CategoryID, this.CurrentThread.ThreadID, BoardParameters.SearchText, 0, 0), true, 3);
							break;
						case BoardThreadUpdateResult.InvalidThread:
							VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadUpdate_Failure"), true);
							break;
					}
				}
				else
					VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_ThreadUpdate_Rejection"), true);
				#endregion
			}
		}
	}

	protected void ThreadMultiFileUploadHelper_RowCreated(Object sender, MultiFileUploadHelperRowCreatedEventArgs e)
	{
		Image iconImage = (Image)e.PreviewCellTemplate.FindControl("PreviewImage");
		TextBox urlTextBox = (TextBox)e.InfoCellTemplate.FindControl("UrlTextBox");

		String fileID = e.CurrentUploadFileInfo.FileID;

		if (e.CurrentUploadFileInfo.ContentType.IndexOf("image") > -1)
		{
			iconImage.AlternateText = "Image";
			iconImage.ImageUrl = BoardUtil.GetAttachmentThumbnailUrl(base.CurrentBoard.ComponentID, fileID);
			urlTextBox.Text = BoardUtil.GetAttachmentFileViewUrl(base.CurrentBoard.ComponentID, fileID);
		}
		else if (e.CurrentUploadFileInfo.ContentType.IndexOf("video") > -1)
		{
			iconImage.AlternateText = "Video";
			iconImage.ImageUrl = ThreadMultiFileUpload.VideoFileImageUrl;
			urlTextBox.Text = BoardUtil.GetAttachmentFileViewUrl(base.CurrentBoard.ComponentID, fileID);
		}
		else if (e.CurrentUploadFileInfo.ContentType.IndexOf("audio") > -1)
		{
			iconImage.AlternateText = "Audio";
			iconImage.ImageUrl = ThreadMultiFileUpload.AudioFileImageUrl;
			urlTextBox.Text = BoardUtil.GetAttachmentFileViewUrl(base.CurrentBoard.ComponentID, fileID);
		}
		else if (e.CurrentUploadFileInfo.ContentType.IndexOf("flash") > -1)
		{
			iconImage.AlternateText = "Flash";
			iconImage.ImageUrl = ThreadMultiFileUpload.FlashFileImageUrl;
			urlTextBox.Text = BoardUtil.GetAttachmentFileViewUrl(base.CurrentBoard.ComponentID, fileID);
		}
		else
		{
			iconImage.AlternateText = "File";
			iconImage.ImageUrl = ThreadMultiFileUpload.CommonFileImageUrl;
			urlTextBox.Text = BoardUtil.GetAttachmentFileDownloadUrl(base.CurrentBoard.ComponentID, fileID);
		}
	}

	protected void ThreadMultiFileUploadHelper_FileAdding(Object sender, MultiFileUploadHelperAddEventArgs e)
	{
		e.Cancel = true;

		if (e.PostedFile.ContentLength <= 0)
		{
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_NotFound"), true);
			return;
		}

		if (ThreadMultiFileUpload.CurrentUploadFileInfoCollection.Count >= ThreadMultiFileUpload.UploadLimit &&
			!(base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard)))
		{
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_CountLimit"), true);
			return;
		}

		if (!AttachmentFileManager.IsAllowExtension(ThreadMultiFileUpload.UploadExtensions, System.IO.Path.GetFileName(e.PostedFile.FileName)))
		{
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_InvalidExtension"), true);
			return;
		}

		if (e.PostedFile.ContentLength > ThreadMultiFileUpload.UploadSizeLimit * 1024 &&
			!(base.CurrentUserInfo.IsAdministrator || base.CurrentUserInfo.IsSysop(base.CurrentBoard)))
		{
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_SizeLimit"), true);
			return;
		}

		//DB, 파일저장
		AttachmentFileInfo attachmentFileInfo = base.CurrentBoard.GetAttachmentFileManager().Add(null, e.PostedFile, e.Description);
		e.NewUploadFileInfo = attachmentFileInfo.UploadFile;
		e.Cancel = false;
	}

	protected void ThreadMultiFileUploadHelper_FileAdded(Object sender, MultiFileUploadHelperAddedEventArgs e)
	{
		if (e.Exception == null)
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_UploadSuccess"), true);
		else
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_UploadFailure"), true);
	}

	protected void ThreadMultiFileUploadHelper_FileRemoving(Object sender, MultiFileUploadHelperRemoveEventArgs e)
	{
		e.Cancel = true;
		base.CurrentBoard.GetAttachmentFileManager().GetAttachmentFileInfo(e.RemoveUploadFileInfo.FileID).Remove();
		e.Cancel = false;
	}

	protected void ThreadMultiFileUploadHelper_FileRemoved(Object sender, MultiFileUploadHelperRemovedEventArgs e)
	{
		if (e.Exception == null)
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_DeleteSuccess"), true);
		else
			VUtility.ShowMessagePanel(Page, VUtility.GetVWebGlobalResource("Board_Do_File_DeleteFailure"), true);
	}

	protected void VoteFormCheckBox_CheckedChanged(Object sender, EventArgs e)
	{
		VoteFormPanel.Visible = VoteFormCheckBox.Checked;
	}
}
